package com.tea.servlet;
import com.tea.entity.Order;
import com.tea.entity.User;
import com.tea.service.PaymentService;
import com.tea.service.OrderService;
import com.tea.service.impl.PaymentServiceImpl;
import com.tea.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

@WebServlet("/payment")
public class PaymentServlet extends HttpServlet {
    private final PaymentService paymentService = new PaymentServiceImpl();
    private final OrderService orderService = new OrderServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");

        try {
            if (user == null) {
                req.setAttribute("errorMsg", "请先登录后再进行支付操作");
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
                return;
            }

            String orderIdStr = req.getParameter("orderId");
            if (orderIdStr == null || orderIdStr.trim().isEmpty()) {
                req.setAttribute("errorMsg", "订单ID不能为空");
                req.getRequestDispatcher("/error.jsp").forward(req, resp);
                return;
            }

            long orderId;
            try {
                orderId = Long.parseLong(orderIdStr);
            } catch (NumberFormatException e) {
                req.setAttribute("errorMsg", "无效的订单ID格式");
                req.getRequestDispatcher("/error.jsp").forward(req, resp);
                return;
            }

            // 获取订单信息
            Order order = orderService.getOrderById(orderId);
            if (order == null) {
                req.setAttribute("errorMsg", "订单不存在");
                req.getRequestDispatcher("/error.jsp").forward(req, resp);
                return;
            }

            // 验证订单归属
            if (order.getUserId() != user.getId()) {
                req.setAttribute("errorMsg", "无权操作此订单");
                req.getRequestDispatcher("/error.jsp").forward(req, resp);
                return;
            }

            // 验证订单状态是否为待付款
            if (order.getStatus() != 0) {
                req.setAttribute("errorMsg", "订单状态异常，无法进行支付");
                req.getRequestDispatcher("/order?action=view&orderId=" + orderId).forward(req, resp);
                return;
            }

            // 设置订单信息到request中
            req.setAttribute("order", order);
            req.setAttribute("orderId", orderId);
            req.setAttribute("totalPrice", order.getTotalAmount());
            req.getRequestDispatcher("/payment.jsp").forward(req, resp);

        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("errorMsg", "获取支付信息异常: " + e.getMessage());
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String action = req.getParameter("action");
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");

        try {
            if (user == null) {
                req.setAttribute("errorMsg", "请先登录后再进行支付操作");
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
                return;
            }

            String orderIdStr = req.getParameter("orderId");
            if (orderIdStr == null || orderIdStr.trim().isEmpty()) {
                req.setAttribute("errorMsg", "订单ID不能为空");
                req.getRequestDispatcher("/error.jsp").forward(req, resp);
                return;
            }

            long orderId;
            try {
                orderId = Long.parseLong(orderIdStr);
            } catch (NumberFormatException e) {
                req.setAttribute("errorMsg", "无效的订单ID格式");
                req.getRequestDispatcher("/error.jsp").forward(req, resp);
                return;
            }

            // 根据不同操作类型处理支付流程
            if ("process".equals(action)) {
                processPayment(req, resp, user, orderId);
            } else if ("verify".equals(action)) {
                verifyPayment(req, resp, orderId);
            } else if ("status".equals(action)) {
                checkPaymentStatus(req, resp, orderId);
            } else {
                req.setAttribute("errorMsg", "无效的操作类型");
                req.getRequestDispatcher("/error.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("errorMsg", "支付处理异常: " + e.getMessage());
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }
    }

    private void processPayment(HttpServletRequest req, HttpServletResponse resp, User user, long orderId) throws Exception {
        HttpSession session = req.getSession();
        try {
            // 验证订单状态
            Order order = paymentService.getOrderById(orderId);
            if (order == null) {
                session.setAttribute("errorMsg", "订单不存在");
                resp.sendRedirect("/error.jsp");
                return;
            }

            // 验证订单归属
            if (order.getUserId() != user.getId()) {
                session.setAttribute("errorMsg", "无权操作此订单");
                resp.sendRedirect("/error.jsp");
                return;
            }

            // 验证订单状态是否为待付款
            if (order.getStatus() != 0) {
                session.setAttribute("errorMsg", "订单状态异常，无法进行支付");
                resp.sendRedirect("/order?action=view&orderId=" + orderId);
                return;
            }

            // 处理支付逻辑
            boolean paymentSuccess = paymentService.processPayment(orderId, user);
            if (paymentSuccess) {
                resp.sendRedirect("/order?action=view&orderId=" + orderId);
            } else {
                session.setAttribute("errorMsg", "支付处理失败，请重试");
                resp.sendRedirect("/order?action=view&orderId=" + orderId);
            }
        } catch (Exception e) {
            throw new Exception("支付处理失败: " + e.getMessage());
        }
    }

    private void verifyPayment(HttpServletRequest req, HttpServletResponse resp, long orderId) throws Exception {
        // 实现支付验证逻辑
        String paymentResult = paymentService.verifyPayment(orderId);
        req.setAttribute("paymentResult", paymentResult);
        req.getRequestDispatcher("/payment-verify.jsp").forward(req, resp);
    }

    private void checkPaymentStatus(HttpServletRequest req, HttpServletResponse resp, long orderId) throws Exception {
        String status = paymentService.getPaymentStatus(orderId);
        Map<String, Object> result = new HashMap<>();
        result.put("orderId", orderId);
        result.put("status", status);
        req.setAttribute("paymentStatus", result);
        req.getRequestDispatcher("/payment-status.jsp").forward(req, resp);
    }
}